from django.http import HttpResponse,JsonResponse
from django.views import View
from libs.captcha.captcha import captcha
from django_redis import get_redis_connection
from libs.yuntongxun.sms import CCP
from celery_tasks.sms.tasks import ccp_send_sms_code
from meiduo_mall.settings.dev import logger
from random import randint
# Create your views here.
class ImageCodeView(View): #图形验证码校验
    def get(self, request, uuid):
        text, image = captcha.generate_captcha() #生成验证码文字,验证码图片
        redis_client = get_redis_connection('verify_image_code') #链接redis数据库
        redis_client.setex('img_%s' %uuid, 300, text) #保存验证码文字,设置有效期
        return HttpResponse(image, content_type='image/jpeg') #返回验证码图片
class SMSCodeView(View): #短信验证码校验
    def get(self, request, mobile):
        uuid = request.GET.get('image_code_id') #获取图形验证码uuid
        image_code = request.GET.get('image_code') #获取图形验证码文本数据
        image_redis_client = get_redis_connection('verify_image_code') #连接redis的图形验证码数据库
        redis_img_code = image_redis_client.get('img_%s' %uuid) #获取uuid所对应的图形验证码文本数据
        sms_redis_client = get_redis_connection('sms_code') #连接redis的短信验证码数据库
        send_flag = sms_redis_client.get('send_flag_%s' % mobile) #获取短信发送标志
        if redis_img_code is None: #判断redis中是否有图形验证码文本
            return JsonResponse({'code':'4001', 'errmsg':'图形验证码过期了'})
        if image_code.lower() != redis_img_code.decode().lower(): #判断redis数据库的图形验证码文本与获取的数据是否相同
            return JsonResponse({'code':'4001', 'errmsg':'图形验证码输入有误'})
        if send_flag: #判断redis中是否存在短信发送标志
            return JsonResponse({'code':'4002', 'errmsg':'发送短信过于频繁'})
        try:
            image_redis_client.delete('img_%s' %uuid) #删除图形验证码文本数据
        except Exception as e:
            logger.error(e)
        sms_code = '%06d' %randint(0, 999999)
        # CCP().send_template_sms('17716958705', [sms_code, 5], 1)
        ccp_send_sms_code.delay(mobile, sms_code)
        pl = sms_redis_client.pipeline()
        pl.setex('sms_%s' %mobile, 300, sms_code) #保存短信验证码至redis数据库
        pl.setex('send_flag_%s' %mobile, 60, 1) #保存短信发送标志至redis数据库
        pl.execute()
        print('当前验证码是:', sms_code)
        return JsonResponse({'code':'0', 'errmsg':'sent message successfully'})